#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
MQTT连接测试程序
用于在PC上测试MQTT连接是否正常
"""

import time
import json
import sys

try:
    import paho.mqtt.client as mqtt
except ImportError:
    print("错误: 请先安装paho-mqtt库")
    print("安装命令: pip install paho-mqtt")
    sys.exit(1)

# MQTT配置参数
MQTT_BROKER = "82.157.22.162"  # MQTT服务器地址
MQTT_PORT = 8083              # MQTT端口号
MQTT_CLIENT_ID = "emqx_MTcxMz"  # 客户端ID
MQTT_KEEPALIVE = 60           # 保活时间
MQTT_PATH = "/mqtt"            # WebSocket路径

# 主题配置
TOPIC_PUBLISH = "maixcam/data"     # 发布主题
TOPIC_SUBSCRIBE = "maixcam/cmd"    # 订阅主题

class MQTTTestClient:
    def __init__(self):
        self.client = None
        self.connected = False
        self.message_count = 0
        
    def on_connect(self, client, userdata, flags, rc):
        """连接回调函数"""
        if rc == 0:
            print(f"✓ MQTT连接成功! 结果代码: {rc}")
            self.connected = True
            # 订阅主题
            client.subscribe(TOPIC_SUBSCRIBE)
            print(f"✓ 已订阅主题: {TOPIC_SUBSCRIBE}")
        else:
            print(f"✗ MQTT连接失败! 结果代码: {rc}")
            print("错误代码说明:")
            print("  1: 协议版本不正确")
            print("  2: 客户端标识符无效")
            print("  3: 服务器不可用")
            print("  4: 用户名或密码错误")
            print("  5: 未授权")
            self.connected = False
    
    def on_disconnect(self, client, userdata, rc):
        """断开连接回调函数"""
        print(f"! MQTT连接断开! 结果代码: {rc}")
        self.connected = False
    
    def on_message(self, client, userdata, msg):
        """消息接收回调函数"""
        try:
            topic = msg.topic
            payload = msg.payload.decode('utf-8')
            print(f"📩 收到消息:")
            print(f"   主题: {topic}")
            print(f"   内容: {payload}")
            self.message_count += 1
            
        except Exception as e:
            print(f"✗ 处理消息时出错: {e}")
    
    def on_publish(self, client, userdata, mid):
        """消息发布回调函数"""
        print(f"✓ 消息发布成功! 消息ID: {mid}")
    
    def connect(self):
        """连接到MQTT服务器"""
        try:
            print("🔗 正在连接MQTT服务器...")
            print(f"   服务器: {MQTT_BROKER}:{MQTT_PORT}")
            print(f"   客户端ID: {MQTT_CLIENT_ID}")
            
            # 创建MQTT客户端（使用WebSocket传输）
            self.client = mqtt.Client(client_id=MQTT_CLIENT_ID, clean_session=True, transport="websockets")
            
            # 设置回调函数
            self.client.on_connect = self.on_connect
            self.client.on_disconnect = self.on_disconnect
            self.client.on_message = self.on_message
            self.client.on_publish = self.on_publish
            
            # 如果需要用户名和密码，可以在这里设置
            # self.client.username_pw_set("username", "password")
            
            # 设置WebSocket路径
            self.client.ws_set_options(path=MQTT_PATH)
            
            # 连接到服务器
            self.client.connect(MQTT_BROKER, MQTT_PORT, MQTT_KEEPALIVE)
            
            # 启动网络循环
            self.client.loop_start()
            
            # 等待连接完成
            for i in range(10):
                if self.connected:
                    break
                time.sleep(1)
                print(f"   等待连接... ({i+1}/10)")
            
            if not self.connected:
                print("✗ 连接超时")
                return False
                
            return True
            
        except Exception as e:
            print(f"✗ 连接失败: {e}")
            return False
    
    def disconnect(self):
        """断开MQTT连接"""
        if self.client:
            self.client.loop_stop()
            self.client.disconnect()
            print("🔌 MQTT连接已断开")
    
    def publish_message(self, message, topic=None):
        """发布消息"""
        if not self.connected or self.client is None:
            print("✗ MQTT未连接，无法发布消息")
            return False
            
        try:
            if topic is None:
                topic = TOPIC_PUBLISH
                
            result = self.client.publish(topic, message)
            if result.rc == mqtt.MQTT_ERR_SUCCESS:
                print(f"📤 发布消息到 {topic}: {message}")
                return True
            else:
                print(f"✗ 消息发布失败: {result.rc}")
                return False
                
        except Exception as e:
            print(f"✗ 发布消息时出错: {e}")
            return False

def main():
    """主函数"""
    print("=" * 50)
    print("🚀 MQTT连接测试程序")
    print("=" * 50)
    
    # 创建MQTT客户端
    mqtt_client = MQTTTestClient()
    
    try:
        # 连接到MQTT服务器
        if not mqtt_client.connect():
            print("❌ MQTT连接失败，程序退出")
            return
        
        print("\n✅ MQTT客户端运行中...")
        print("📝 测试说明:")
        print(f"   - 发布主题: {TOPIC_PUBLISH}")
        print(f"   - 订阅主题: {TOPIC_SUBSCRIBE}")
        print("   - 输入消息并按回车发送")
        print("   - 输入 'quit' 或按Ctrl+C退出\n")
        
        # 发布测试消息
        test_data = {
            "type": "test",
            "device": "PC测试客户端",
            "timestamp": int(time.time()),
            "message": "连接测试成功"
        }
        mqtt_client.publish_message(json.dumps(test_data, ensure_ascii=False))
        
        # 交互式消息发送
        while True:
            try:
                user_input = input("请输入要发送的消息 (输入'quit'退出): ").strip()
                
                if user_input.lower() == 'quit':
                    break
                    
                if user_input:
                    # 构造消息数据
                    message_data = {
                        "type": "user_message",
                        "timestamp": int(time.time()),
                        "content": user_input
                    }
                    mqtt_client.publish_message(json.dumps(message_data, ensure_ascii=False))
                
            except EOFError:
                break
            
    except KeyboardInterrupt:
        print("\n⚠️ 接收到退出信号")
    except Exception as e:
        print(f"❌ 程序运行错误: {e}")
    finally:
        # 清理资源
        mqtt_client.disconnect()
        print("👋 程序结束")

if __name__ == "__main__":
    main()